// ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
var vm_tma_demo = new Vue({
  el: ".tma_caculate",
  delimiters: ["[[", "]]"],
  data: {
    myChart: null,
    ekelund_range_chart: null,
    chartdata_original: [],
    image_lines: [],
    bl_time_tick: [],
    canvas_size: [500, 400],
    image_size: [0, 0, 500, 500],
    original_image_size: [0, 0, 500, 500],
    series_lines: [],
    tma_instance_key: "",
    original_series_lines: [],
    predict_tracks: [],
    tma_prediction_processing: false,
    toggle_explaination: true,
    legend: {},
    pd_with_track: {},
    pd_without_track: {},
    track_detected: false,
    ekelund_range: null,
    ekelund_range_cross_spd: 10,
    ekelund_range_spd_top: 60,
    ekelund_range_spd_btm: 3,
    ekelund_range_draw_processing: false,
    active_plus_data_id: 9999,
    own_sub_spd: 0,
    own_sub_course: 0,
    target_sub_spd: 0,
    target_bearing: 0,
    predict_track_ratio: 0,
    own_cross_spd_list: [],
  },
  created() {
    window.addEventListener("resize", this.myEventHandler, false);
  },
  destroyed() {
    window.removeEventListener("resize", this.myEventHandler, false);
  },
  mounted() {
    this.tma_init_draw();
  },
  methods: {
    convert_to_chartdata() {
      let items = this.image_lines;
      let series = [];
      for (let i = 0; i < items.length; i++) {
        series.push({
          id: this.bl_time_tick[i],
          name: this.bl_time_tick[i],
          type: "line",
          color: "#5470c6",
          symbolSize: 0,
          symbol: "circle",
          emphasis: {
            focus: "series",
          },
          triggerLineEvent: true,
          data: [
            [items[i][0], items[i][1]],
            [items[i][2], items[i][3]],
          ],
        });
      }
      this.series_lines = series;
      this.original_series_lines = JSON.parse(JSON.stringify(series));
    },
    submit_image_file(e) {
      if (this.tma_prediction_processing == true) {
        alert("TMA prediction in process, wait for it to complete first!");
        return;
      } else {
        this.tma_prediction_processing = true;
      }
      let files = e.target.files;
      let formData = new FormData();
      formData.append("files", files[0]);
      let url = "/tutorial/tma-image-upload/";
      let headers = {
        "Content-Type": "multipart/form-data",
      };
      this.predict_track_ratio = 0;
      axios
        .post(url, formData, { headers: headers })
        .then((e) => {
          this.pd_without_track = {};
          this.pd_with_track = {};
          this.predict_tracks = [];
          this.legend = {};
          this.active_plus_data_id = 9999;
          this.image_lines = e.data.lines;
          this.canvas_size = e.data.canvas_size;
          this.image_size = e.data.image_size;
          this.original_image_size = JSON.parse(
            JSON.stringify(this.image_size),
          );
          this.tma_instance_key = e.data.tma_instance_key;
          this.bl_time_tick = e.data.bl_time_tick;
          this.convert_to_chartdata();
          // console.log("=================================");
          // console.log(this.bl_time_tick);
          // console.log(e.data.image_size);
          this.myChart.resize({
            height: this.canvas_size[0] * 1.1,
            width: this.canvas_size[1] * 1.1,
          });
          this.tma_prediction_processing = false;
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
          this.tma_prediction_processing = false;
        });
    },
    submit_new_tma_lines() {
      if (this.series_lines.length < 3) {
        alert("At least 3 bearing lines required for track prediction!");
        return;
      }
      this.predict_track_ratio = 0;
      this.active_plus_data_id = 9999;
      // console.log(this.tma_instance_key);
      if (this.tma_instance_key === "") {
        return;
      }
      if (this.tma_prediction_processing == true) {
        return;
      }
      this.tma_prediction_processing = !this.tma_prediction_processing;
      let new_tma_lines = [];
      for (let i = 0; i < this.series_lines.length; i++) {
        let item = this.series_lines[i];
        new_tma_lines.push([
          [item.data][0][0][0],
          [item.data][0][0][1],
          [item.data][0][1][0],
          [item.data][0][1][1],
        ]);
      }
      this.ekelund_range = null;
      this.ekelund_range_chart.clear();
      axios
        .post("/tutorial/tma-process/", {
          tma_instance_key: this.tma_instance_key,
          new_tma_lines: new_tma_lines,
          new_bl_time_tick: this.bl_time_tick,
          own_sub_spd: this.own_sub_spd,
          own_sub_course: this.own_sub_course,
          target_sub_spd: this.target_sub_spd,
        })
        .then((e) => {
          let data = e.data;
          if (data.code != 0) {
            alert("Failed to predict target track");
            this.tma_prediction_processing = !this.tma_prediction_processing;
            return;
          }
          // console.log("=================================");
          // console.log(data);
          this.image_size = data.image_size;
          this.pd_without_track = data.pd_without_track;
          let series = [];
          let track = data.pd_without_track.track;
          series.push({
            id: 1001,
            name: "Estimated_track",
            type: "line",
            color: "#57bb40",
            data: [
              [track[0], track[1]],
              [track[2], track[3]],
            ],
          });
          this.track_detected = data.track_detected;
          this.predict_track_ratio = data.pd_track_ratio;
          if (data.track_detected == true) {
            this.pd_with_track = data.pd_with_track;
            let track = data.pd_with_track.track;
            series.push({
              id: 1000,
              name: "Detected_track",
              type: "line",
              color: "#e10033",
              data: [
                [track[0], track[1]],
                [track[2], track[3]],
              ],
            });
          }
          this.predict_tracks = series;
          this.tma_prediction_processing = !this.tma_prediction_processing;
          // ekelund_range_chart
          this.ekelund_range = data.ekelund_range;
          this.ekelund_range_spd_btm = data.ekelund_range_spd_btm;
          this.ekelund_range_spd_top = data.ekelund_range_spd_top;
          this.redrawEkelundChart();
          // ekelund_range_enhanced_chart
          // if (!Array.isArray(data.ekelund_range_enhanced)) {
          if (data.ekelund_range_enhanced != null) {
            this.redrawEkelundEnhancedChart(data.ekelund_range_enhanced);
            this.own_cross_spd_list = data.own_cross_spd_list;
          }
          console.log(this.own_cross_spd_list)
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
          this.tma_prediction_processing = !this.tma_prediction_processing;
        });
    },
    myEventHandler(e) {
      let w = this.$refs.div_canvas.offsetWidth;
      let h = Math.abs(
        Math.ceil(
          w *
            (Math.ceil(this.image_size[3] - this.image_size[1]) /
              Math.ceil(this.image_size[2] - this.image_size[0]))
        )
      );
      // let h = Math.ceil(
      //   w *
      //     (Math.ceil(this.image_size[3] * 1.05) /
      //       Math.ceil(this.image_size[2] * 1.05)),
      // );
      this.myChart.resize({
        width: w,
        height: h,
      });
      this.ekelund_range_enhance_chart.resize({
        width: w,
        height: 200,
      });
      w = this.$refs.div_canvas_02.offsetWidth;
      h = Math.ceil(w / 2);
      this.ekelund_range_chart.resize({
        width: w,
        height: h,
      });
    },
    hl_line(data_id) {
      let data = this.series_lines.find((obj) => obj.id === data_id)["data"];
      this.active_plus_data_id = data_id;
      let series = [
        {
          id: data_id,
          // name: data_id,
          type: "line",
          symbolSize: 0,
          symbol: "circle",
          triggerLineEvent: true,
          emphasis: {
            focus: "series",
          },
          data: data,
          color: "#fabd2f",
        },
      ];
      this.myChart.setOption({
        series: series,
      });
    },
    not_hl_line(data_id) {
      this.active_plus_data_id = 99999;
      let data = this.series_lines.find((obj) => obj.id === data_id)["data"];
      let series = [
        {
          id: data_id,
          type: "line",
          symbolSize: 0,
          symbol: "circle",
          triggerLineEvent: true,
          emphasis: {
            focus: "series",
          },
          data: data,
          color: "#5470c6",
        },
      ];
      this.myChart.setOption({
        series: series,
      });
    },
    delete_hl_line(data_id) {
      if (this.tma_prediction_processing == true) {
        alert("TMA prediction in process, wait for it to complete first!");
        return;
      }
      let del_idx = this.series_lines.findIndex((item) => {
        return (
          JSON.stringify(item["id"]) === JSON.stringify(data_id) ||
          item["id"] === JSON.stringify(data_id)
        );
      });
      this.series_lines = this.series_lines.filter((obj) => obj.id !== data_id);
      if (del_idx < this.series_lines.length) {
        this.active_plus_data_id = this.series_lines[del_idx]["id"];
      }
    },
    insert_a_tick(data_id) {
      if (this.tma_prediction_processing == true) {
        alert("TMA prediction in process, wait for it to complete first!");
        return;
      }
      this.active_plus_data_id = data_id + 1;
      this.series_lines.forEach((item, idx, arr) => {
        if (item["id"] >= data_id) {
          arr[idx]["id"]++;
        }
      });
    },
    delete_a_tick(data_id, index) {
      if (this.tma_prediction_processing == true) {
        alert("TMA prediction in process, wait for it to complete first!");
        return;
      }
      if (index == 0) {
        // alert("Can not decrease below 0!");
        return;
      }

      if (
        parseInt(this.series_lines[index - 1]["id"]) + 1 >=
        parseInt(data_id)
      ) {
        // @TODO add blink effect
        // alert("Minimum time seperation reached");
        return;
      }
      this.series_lines.forEach((item, idx, arr) => {
        if (idx >= index) {
          arr[idx]["id"]--;
        }
      });
      this.active_plus_data_id = data_id - 1;
    },
    redrawChart() {
      let series = JSON.parse(JSON.stringify(this.series_lines));
      if (this.predict_tracks.length > 0) {
        for (let i in this.predict_tracks) {
          series.push(this.predict_tracks[i]);
        }
      }
      let legend_data = [];
      if (this.predict_tracks.length >= 1) {
        legend_data.push({
          name: "Estimated_track",
          icon: "circle",
          triggerLineEvent: true,
          emphasis: {
            focus: "series",
          },
          textStyle: {
            color: "#57bb40",
          },
        });
      }
      if (this.predict_tracks.length == 2) {
        legend_data.push({
          name: "Detected_track",
          icon: "circle",
          triggerLineEvent: true,
          emphasis: {
            focus: "series",
          },
          textStyle: {
            color: "#e10033",
          },
        });
      }
      this.legend = {
        data: legend_data,
        orient: "horizontal",
      };
      let xAxis = {
        min: this.image_size[0] - 10,
        max: Math.ceil(this.image_size[2] * 1.05),
        type: "value",
        axisLine: { onZero: false },
        scale: true,
        axisLabel: { show: false },
        axisTick: { show: false },
        show: false,
      };
      let yAxis = {
        min: this.image_size[1] * 0.95,
        max: Math.ceil(this.image_size[3] * 1.05),
        show: false,
        type: "value",
        axisLine: { onZero: false },
        scale: true,
        axisLabel: { show: false },
        axisTick: { show: false },
      };
      this.myChart.setOption(
        {
          // title: {
          //   text: "TMA Prediction",
          //   left: "center",
          // },
          xAxis: xAxis,
          yAxis: yAxis,
          series: series,
          grid: {
            left: "0",
            right: "0",
            top: "0",
            bottom: "0",
            // containLabel: true,
          },
          legend: this.legend,
        },
        // { replaceMerge: "series" },
        { notMerge: true },
      );
      let w = this.$refs.div_canvas.offsetWidth;
      // let h = Math.ceil(
      //   w *
      //     (Math.ceil(this.image_size[3] * 0.95) /
      //       Math.ceil(this.image_size[2] * 1.05)),
      // );
      let h = Math.abs(
        Math.ceil(
          w *
            (Math.ceil(this.image_size[3] - this.image_size[1]) /
              Math.ceil(this.image_size[2] - this.image_size[0]))
        )
      );
      this.myChart.resize({
        width: w,
        height: h,
      });
    },
    redrawEkelundChart() {
      let x_data = this.series_lines.map((item) => "t" + item.id);
      const spd = parseInt(this.ekelund_range_cross_spd);
      let ekelund_range_series = [];
      for (let i = spd - 2; i <= spd + 2; i++) {
        if (i < this.ekelund_range_spd_btm || i >= this.ekelund_range_spd_top) {
          continue;
        } else {
          let data = this.ekelund_range.map((item) => item[i]);
          if (i === spd) {
            ekelund_range_series.push({
              id: i,
              name: i,
              type: "line",
              // stack: "Total",
              data: data,
              color: "#ea7ccc",
            });
          } else {
            ekelund_range_series.push({
              id: i,
              name: i,
              type: "line",
              // stack: "Total",
              data: data,
              color: "#73c0de",
            });
          }
        }
      }
      // let legend_data = [];
      let option = {
        title: {
          text: "Ekelund Ranging",
          left: "center",
        },
        tooltip: {
          trigger: "axis",
        },
        // legend: {
        //   data: [4, 5, 6],
        // },
        grid: {
          left: "0",
          right: "10",
          bottom: "0",
          top: "30",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: x_data,
          alignTicks: true,
        },
        yAxis: {
          type: "value",
          // min: "dataMin",
          // max: "dataMax",
          // max: function (value) {
          //   return value.max ;
          // },
          // axisLine: { onZero: true },
          scale: true,
          // axisLabel: { show: true },
          // axisTick: { show: true },
        },
        series: ekelund_range_series,
      };
      this.ekelund_range_chart.setOption(option, { notMerge: true });
    },
    redrawEkelundEnhancedChart(data) {
      let x_data = this.series_lines.map((item) => "t" + item.id);
      let series = [];
      // let legend_data = [];

      series.push({
        id: 1,
        name: 1,
        type: "line",
        data: data["without_track"],
        color: "#57bb40",
      });
      if (data["track_detected"]) {
        series.push({
          id: 2,
          name: 2,
          type: "line",
          data: data["with_track"],
          color: "#e10033",
        });
      }
      let option = {
        title: {
          text: "Ekelund Ranging using track info",
          left: "center",
        },
        tooltip: {
          trigger: "axis",
        },
        // legend: {
        //   data: [4, 5, 6],
        // },
        grid: {
          left: "0",
          right: "10",
          bottom: "0",
          top: "30",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: x_data,
          alignTicks: true,
        },
        yAxis: {
          type: "value",
          // min: "dataMin",
          // max: "dataMax",
          // max: function (value) {
          //   return value.max ;
          // },
          // axisLine: { onZero: true },
          scale: true,
          // axisLabel: { show: true },
          // axisTick: { show: true },
        },
        series: series,
      };
      this.ekelund_range_enhance_chart.setOption(option, { notMerge: true });
    },
    tma_init_draw() {
      this.myChart = echarts.init(document.getElementById("chart"));
      this.ekelund_range_chart = echarts.init(
        document.getElementById("ekelund_range_chart"),
      );
      this.ekelund_range_enhance_chart = echarts.init(
        document.getElementById("ekelund_range_enhance_chart"),
      );
      this.series_lines = [];
      // this.series_lines = [
      //   {
      //     id: 1,
      //     type: "line",
      //     color: "#57bb40",
      //     data: [
      //       [60, 400],
      //       [60, 100],
      //       '-',
      //       [60, 250],
      //       [140, 250],
      //       '-',
      //       [140, 400],
      //       [140, 100],
      //       '-',
      //     ],

      //   },
      // ];
    },
    resetdata() {
      if (this.tma_prediction_processing == true) {
        return;
      }
      this.series_lines = JSON.parse(
        JSON.stringify(this.original_series_lines),
      );
      this.image_size = JSON.parse(JSON.stringify(this.original_image_size));
    },
  },
  watch: {
    series_lines: {
      handler: function () {
        this.redrawChart();
        this.bl_time_tick = this.series_lines.map((v) => {
          return v.id;
        });
      },
      deep: true,
      immediate: false,
    },
    predict_tracks: {
      handler: function () {
        this.redrawChart();
      },
      deep: false,
      immediate: false,
    },
    ekelund_range_cross_spd: {
      handler: function () {
        this.redrawEkelundChart();
      },
      deep: false,
      immediate: false,
    },
  },
  computed: {
    target_bearing_mirror() {
      let course = parseInt(this.own_sub_course);
      let br = parseInt(this.target_bearing);
      let angle_diff = Math.abs(course - br);
      if (angle_diff > 180) {
        angle_diff = 360 - angle_diff;
      }
      let br1 = course - angle_diff;
      let br2 = course + angle_diff;
      if (br1 < 0) {
        br1 = 360 + br1;
      }
      if (br1 >= 360) {
        br1 = br1 - 360;
      }
      if (br2 < 0) {
        br2 = 360 + br2;
      }
      if (br2 >= 360) {
        br2 = br2 - 360;
      }

      return br1 != br ? br1 : br2;
    },
  },
});
